package com.yupi.oj.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.oj.common.ErrorCode;
import com.yupi.oj.constant.CommonConstant;
import com.yupi.oj.exception.BusinessException;
import com.yupi.oj.exception.ThrowUtils;
import com.yupi.oj.judge.JudgeService;
import com.yupi.oj.mapper.QuestionSubmitMapper;
import com.yupi.oj.mapper.TagMapper;
import com.yupi.oj.model.dto.questionSubmit.JudgeInfo;
import com.yupi.oj.model.dto.questionSubmit.QuestionSubmitAddRequest;
import com.yupi.oj.model.dto.questionSubmit.QuestionSubmitQueryRequest;
import com.yupi.oj.model.entity.Question;
import com.yupi.oj.model.entity.QuestionSubmit;
import com.yupi.oj.model.entity.QuestionSubmitSimple;
import com.yupi.oj.model.entity.User;
import com.yupi.oj.model.enums.QuestionSubmitLanguage;
import com.yupi.oj.model.enums.QuestionSubmitStatus;
import com.yupi.oj.model.vo.*;
import com.yupi.oj.service.QuestionService;
import com.yupi.oj.service.QuestionSubmitService;
import com.yupi.oj.service.UserService;
import com.yupi.oj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 题目提交服务实现
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit> implements QuestionSubmitService {
    @Resource
    private QuestionService questionService;
    @Resource
    private UserService userService;
    @Resource
    private TagMapper tagMapper;
    @Resource
    private QuestionSubmitMapper questionSubmitMapper;
    @Resource
    @Lazy
    private JudgeService judgeService;

    /**
     * 题目提交
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public QuestionSubmitVO doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        //校验编程语言是否合法
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguage enumByValue = QuestionSubmitLanguage.getEnumByValue(language);
        if (enumByValue == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }
        // 判断实体是否存在，根据类别获取实体
        Long questionId = questionSubmitAddRequest.getQuestionId();
        Question question = null;
        if (questionId != null) {
            question = questionService.getById(questionId);
            ThrowUtils.throwIf(question == null, ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        } else {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long userId = loginUser.getId();
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(questionSubmitAddRequest.getLanguage());
        questionSubmit.setQuestionId(questionSubmitAddRequest.getQuestionId());
        //设置初始状态
        questionSubmit.setStatus(QuestionSubmitStatus.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        QuestionSubmitVO questionSubmitVO = null;
        // 避免用户反复提交
        synchronized (String.valueOf(userId).intern()){
            boolean save = this.save(questionSubmit);
            if (!save) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入失败");
            }
            //修改题目提交数量
            Integer num = question.getSubmitNum() + 1;
            question.setSubmitNum(num);
            boolean b = questionService.updateById(question);
            if (!b) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目修改失败");
            }
            //获得判题结果
            questionSubmitVO = judgeService.doJudge(questionSubmit.getId());
        }
        //根据条件修改题目通过数量
        Integer status = questionSubmitVO.getStatus();
        Integer acceptedNum = question.getAcceptedNum() + 1;
        if (Objects.equals(status, QuestionSubmitStatus.SUCCESS.getValue())) {
            question.setAcceptedNum(acceptedNum);
            boolean update = questionService.updateById(question);
            if (!update) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目修改失败");
            }
        }
        return questionSubmitVO;
    }

    /**
     * 获取查询包装类
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(language), "language", language);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    @Override
    public QueryWrapper<QuestionSubmit> getSimpleQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        queryWrapper.select("questionId,status,judgeInfo,userId,createTime,language");
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(language), "language", language);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        long userId = questionSubmit.getUserId();
        //脱敏,只有当前用户和管理员可以得到某些信息
        if (userId != loginUser.getId() && !userService.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, HttpServletRequest request) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        User loginUser = userService.getLoginUser(request);
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().map(questionSubmit -> {
            return getQuestionSubmitVO(questionSubmit, loginUser);
        }).collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }

    @Override
    public UserAnswerStatisticsVO getUserAnswerStatisticVO(User loginUser) {
        // 查询数据库
        List<QuestionSubmitDataVO> questionSubmitDataVOS = questionSubmitMapper.selectSubmitData(loginUser.getId());
        if (CollUtil.isEmpty(questionSubmitDataVOS)) {
            return new UserAnswerStatisticsVO();
        }
        UserAnswerStatisticsVO userAnswerStatisticsVO = new UserAnswerStatisticsVO();
        // 计算题解总数，并且去重
        List<QuestionSubmitDataVO> successData = questionSubmitDataVOS.stream()
                .filter(data -> data.getStatus().equals(QuestionSubmitStatus.SUCCESS.getValue()))
                .distinct()
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(successData)) {
            userAnswerStatisticsVO.setTotalCompleteNum(successData.size());
        }
        // 设置提交总数
        userAnswerStatisticsVO.setTotalSubmitNum(questionSubmitDataVOS.size());
        // 计算通过数
        List<Long> acceptQuestionIdList = questionSubmitDataVOS.stream()
                .filter(data -> data.getStatus().equals(QuestionSubmitStatus.SUCCESS.getValue()))
                .map(QuestionSubmitDataVO::getQuestionId)
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(acceptQuestionIdList)) {
            userAnswerStatisticsVO.setTotalAcceptedNum(acceptQuestionIdList.size());
        }
        // 统计不同难度题目的完成数量
        // 按难度分组统计
        Map<String, Long> levelCountMap = successData.stream()
                .collect(Collectors.groupingBy(QuestionSubmitDataVO::getLevel, Collectors.counting()));
        // 转换为 List<QuestionCompleteNumVO>
        List<UserAnswerStatisticsVO.QuestionCompleteNumVO> questionCompleteNumVOS = levelCountMap.entrySet().stream()
                .map(entry -> {
                    UserAnswerStatisticsVO.QuestionCompleteNumVO vo = new UserAnswerStatisticsVO.QuestionCompleteNumVO();
                    vo.setLeave(entry.getKey()); // 设置难度
                    vo.setCompleteNum(entry.getValue().intValue()); // 设置完成数量
                    return vo;
                }).collect(Collectors.toList());
        // 设置到 userAnswerStatisticsVO 中
        if (CollUtil.isNotEmpty(questionCompleteNumVOS)) {
            userAnswerStatisticsVO.setLeaveQuestionNumList(questionCompleteNumVOS);
        }
        // 统计标签数量
        if(CollUtil.isNotEmpty(successData)){
            // 计算通过的题目Id(去重)
            Set<Long> questionIds = successData.stream()
                    .map(QuestionSubmitDataVO::getQuestionId)
                    .collect(Collectors.toSet());
            List<QuestionCompleteWithTagNum> questionCompleteWithTagNumList = tagMapper.selectQuestionCompleteWithTagNum(questionIds);
            if (CollUtil.isNotEmpty(questionCompleteWithTagNumList)) {
                userAnswerStatisticsVO.setQuestionCompleteWithTagNumList(questionCompleteWithTagNumList);
            }
        }
        return userAnswerStatisticsVO;
    }

    @Override
    public CustomPage<QuestionSubmitSimpleVO> listQuestionSubmitSimpleVO(QuestionSubmitQueryRequest questionSubmitQueryRequest, User loginUser) {
        // 查询question_submit表
        int current = questionSubmitQueryRequest.getCurrent();
        int pageSize = questionSubmitQueryRequest.getPageSize();
        int currentSize = (current - 1) * pageSize;
        // 查询出最近提交的且不重复的提交列表
        List<QuestionSubmitSimple> questionSubmitList = questionSubmitMapper.listQuestionSubmitSimpleVO(questionSubmitQueryRequest,currentSize);
        if(CollUtil.isEmpty(questionSubmitList)){
            return new CustomPage<>();
        }
        // 转换为类型QuestionSubmitSimpleVO
        List<QuestionSubmitSimpleVO> questionSubmitSimpleVOList = questionSubmitList.stream()
                .map(questionSubmit -> {
                    QuestionSubmitSimpleVO questionSubmitSimpleVO = new QuestionSubmitSimpleVO();
                    BeanUtils.copyProperties(questionSubmit, questionSubmitSimpleVO);
                    if (questionSubmit.getJudgeInfo() != null) {
                        questionSubmitSimpleVO.setJudgeInfo(JSONUtil.toBean(questionSubmit.getJudgeInfo(), JudgeInfo.class));
                    }
                    if (questionSubmit.getTags() != null) {
                        questionSubmitSimpleVO.setTags(JSONUtil.toList(questionSubmit.getTags(), String.class));
                    }
                    return questionSubmitSimpleVO;
                })
                .collect(Collectors.toList());
        // 计算每个题目总提交数
        QueryWrapper<QuestionSubmit> questionSubmitQueryWrapper = new QueryWrapper<>();
        questionSubmitQueryWrapper.select("questionId, count(*) as totalSubmitNum")
                .eq("userId", questionSubmitQueryRequest.getUserId())
                .groupBy("questionId");
        List<Map<String, Object>> maps = this.listMaps(questionSubmitQueryWrapper);
        maps.forEach(map -> {
                    Long questionId = Long.valueOf(map.get("questionId").toString());
                    Integer totalSubmitNum = Integer.valueOf(map.get("totalSubmitNum").toString());
                    questionSubmitSimpleVOList.stream()
                            .filter(questionSubmitSimpleVO -> questionSubmitSimpleVO.getQuestionId().equals(questionId))
                            .forEach(questionSubmitSimpleVO -> questionSubmitSimpleVO.setTotalSubmitNum(totalSubmitNum));
                });
        // 查询最近提交的且不重复的提交数量
        long totalCount = questionSubmitMapper.selectTotalCount(questionSubmitQueryRequest);
        CustomPage<QuestionSubmitSimpleVO> questionSubmitSimpleVOCustomPage = new CustomPage<>();
        questionSubmitSimpleVOCustomPage.setData(questionSubmitSimpleVOList);
        questionSubmitSimpleVOCustomPage.setTotalCount(totalCount);
        return questionSubmitSimpleVOCustomPage;
    }

    @Override
    public CustomPage<QuestionSubmitSimpleVO> listQuestionSubmitSimpleVOByQuestionId(QuestionSubmitQueryRequest questionSubmitQueryRequest, User loginUser) {
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        int current = questionSubmitQueryRequest.getCurrent();
        int pageSize = questionSubmitQueryRequest.getPageSize();
        int currentSize = (current - 1) * pageSize;
        // 校验题目是否存在
        Question question = questionService.getById(questionId);
        ThrowUtils.throwIf(question == null, ErrorCode.NOT_FOUND_ERROR,"题目不存在");
        // 查询同一题目的提交列表
        QueryWrapper<QuestionSubmit> questionSubmitQueryWrapper = new QueryWrapper<>();
        questionSubmitQueryWrapper
                .select("id","language","questionId","judgeInfo","createTime","status")
                .eq("questionId", questionId)
                .eq("userId", loginUser.getId())
                .orderByDesc("createTime")
                .last("limit "+ currentSize + "," + pageSize);
        List<QuestionSubmit> questionSubmitList = this.list(questionSubmitQueryWrapper);
        if(CollUtil.isEmpty(questionSubmitList)){
            return new CustomPage<>();
        }
        List<QuestionSubmitSimpleVO> questionSubmitSimpleVOList = questionSubmitList.stream()
                .map(questionSubmit -> {
                    QuestionSubmitSimpleVO questionSubmitSimpleVO = new QuestionSubmitSimpleVO();
                    BeanUtils.copyProperties(questionSubmit, questionSubmitSimpleVO);
                    if (questionSubmit.getJudgeInfo() != null) {
                        questionSubmitSimpleVO.setJudgeInfo(JSONUtil.toBean(questionSubmit.getJudgeInfo(), JudgeInfo.class));
                    }
                    return questionSubmitSimpleVO;
                })
                .collect(Collectors.toList());
        CustomPage<QuestionSubmitSimpleVO> questionSubmitSimpleVOCustomPage = new CustomPage<>();
        // 设置data
        if (CollUtil.isNotEmpty(questionSubmitSimpleVOList)){
            questionSubmitSimpleVOCustomPage.setData(questionSubmitSimpleVOList);
        }
        // 查询同一题目提交数量
        questionSubmitQueryWrapper = new QueryWrapper<>();
        questionSubmitQueryWrapper.select("count(*) as totalCount")
                .eq("questionId", questionId)
                .eq("userId", loginUser.getId());
        List<Map<String, Object>> maps = questionSubmitMapper.selectMaps(questionSubmitQueryWrapper);
        maps.forEach(map -> {
                    Long totalCount = Long.valueOf(map.get("totalCount").toString());
                    questionSubmitSimpleVOCustomPage.setTotalCount(totalCount);
                });
        return questionSubmitSimpleVOCustomPage;
    }
}
